package com.example.demo;

import org.docx4j.Docx4J;
import org.docx4j.dml.wordprocessingDrawing.Inline;
import org.docx4j.model.structure.SectionWrapper;
import org.docx4j.model.table.TblFactory;
import org.docx4j.openpackaging.exceptions.InvalidFormatException;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.*;
import org.docx4j.relationships.Relationship;
import org.docx4j.toc.TocGenerator;
import org.docx4j.wml.*;

import java.io.*;
import java.util.List;


/**
 * docx4j 代码demo
 */
public class Docx4jDemo {
    /**
     * 输出的docx文件路径
     */
    static final String OUTPUT_DOCX_PATH="/Users/wuxinbo/poiDemo/outPutDocx.docx";
    /**
     * 测试html路径
     */
    static final String TEST_HTML="/Users/wuxinbo/poiDemo/test.html";
    /**
     * 测试图片地址
     */
    static final String IMG_PATH="/Users/wuxinbo/poiDemo/21.jpg";
    /**
     * 工厂
     */
    private static  ObjectFactory factory =new ObjectFactory();
    /**
     *
     */
    public static void main(String args[]) throws Exception {
        WordprocessingMLPackage mlPackage =WordprocessingMLPackage.createPackage();
        //获取主文档
        MainDocumentPart mainDocumentPart = mlPackage.getMainDocumentPart();
//        mainDocumentPart.addStyledParagraphOfText("Heading1","标题一");
//        mainDocumentPart.addStyledParagraphOfText("Heading2","标题2");
//        P p = mainDocumentPart.addParagraphOfText("hello,world");
//        mainDocumentPart.addParagraphOfText("今天天气真不错2");
        //增加Header和Footer
        createHeader(mlPackage);
        //创建图片段落
//        createImaParagh(mlPackage);
        BufferedReader reader =new BufferedReader(new FileReader(TEST_HTML));
        StringBuilder builder =new StringBuilder();
        reader.lines().forEach(str->builder.append(str));
        mainDocumentPart.addAltChunk(AltChunkType.Html,builder.toString().getBytes());
        TocGenerator generator =new TocGenerator(mlPackage);
//        createTable(mlPackage);
        generator.generateToc( 0,    "TOC \\o \"1-3\" \\h \\z \\u ", true);
        mlPackage.save(new File(OUTPUT_DOCX_PATH), Docx4J.FLAG_SAVE_ZIP_FILE);
    }
    /**
     * 创建图文段落
     * @param mlPackage
     */
    private static void createImaParagh(WordprocessingMLPackage mlPackage) throws Exception {
        P p = factory.createP();
        Text text = factory.createText();
        text.setValue("下面是图片嵌套");
        R r =factory.createR();
        r.getContent().add(text);
        p.getContent().add(r);
        BinaryPartAbstractImage image =BinaryPartAbstractImage.
                createImagePart(mlPackage,new File(IMG_PATH));
        Inline imageInline = image.createImageInline("21", "21", 0, 1, true);
        Drawing drawing = factory.createDrawing();
        r.getContent().add(drawing);
        drawing.getAnchorOrInline().add(imageInline);
        mlPackage.getMainDocumentPart().addObject(p);
    }

    /**
     * 创建表格
     * @param mlPackage
     * @throws Exception
     */
    static void createTable(WordprocessingMLPackage mlPackage) throws Exception{
        int row=3;
        int col=3;
        Tbl table = TblFactory.createTable(row,col,1);
        int index =0;
        for (Object o : table.getContent()) {
            for (Object o1 : ((Tr) o).getContent()) {
                index++;
                Tc tc = (Tc) o1;
                Text text = factory.createText();
                text.setValue("hello"+index);
                P p = factory.createP();
                R r = factory.createR();
                p.getContent().add(r);
                r.getContent().add(text);
                tc.getContent().set(0,p);
            }
        }
        mlPackage.getMainDocumentPart().addObject(table);
    }
    /**
     * 创建页眉
     */
    public static void createHeader(WordprocessingMLPackage mlPackage) throws InvalidFormatException {
        HeaderPart headerPart =new HeaderPart();
        Relationship relationship = mlPackage.getMainDocumentPart().addTargetPart(headerPart);
        List<SectionWrapper> sections = mlPackage.getDocumentModel().getSections();
        sections.forEach(item->{
            SectPr sectPr =item.getSectPr();
            HeaderReference headerReference = factory.createHeaderReference();
            headerReference.setType(HdrFtrRef.DEFAULT);
            System.out.println("relationShipId is "+relationship.getId());
            headerReference.setId(relationship.getId());
            sectPr.getEGHdrFtrReferences().add(headerReference);
        });
        Hdr hdr = factory.createHdr();
        hdr.getContent().add(createR());
        headerPart.setContents(hdr);
    }
    public static P createR(){
        P p = factory.createP();
        R r =factory.createR();
        Text text = factory.createText();
        text.setValue("重庆常朝科技有限公司");
        PPr pPr = factory.createPPr();
        Jc jc = factory.createJc();
        jc.setVal(JcEnumeration.RIGHT);
        pPr.setJc(jc);
        p.setPPr(pPr);
        r.getContent().add(text);
        p.getContent().add(r);

        return p;
    }
}
